package models

import (
	"gorm.io/gorm"
)

type UserLog struct {
	Id            int   `gorm:"column:id"`
	Acid          int   `gorm:"column:acid;uniqueIndex"`
	LoginTime     int64 `gorm:"column:login_time"`
	OperationTime int64 `gorm:"column:operation_time"`
	FreeCreadit   int   `gorm:"column:free_creadit"`
	MemberCreadit int   `gorm:"column:member_creadit"`
	AddedCreadit  int   `gorm:"column:added_creadit"`
	AllCreadit    int   `gorm:"column:all_creadit"`
}

func SaveUserLog(acid int, login_time int64, operation_time int64) (bool, error) {

	var userLog UserLog
	// 检查记录是否存在
	var userLogs []UserLog
	result := db.Where("acid = ?", acid).Find(&userLogs)
	if result.RowsAffected == 0 {
		// 记录不存在：根据存在的字段创建新记录
		newUserLog := UserLog{Acid: acid}
		if login_time > 0 {
			newUserLog.LoginTime = login_time
		} else if operation_time > 0 {
			newUserLog.OperationTime = operation_time
		} else {
			return false, gorm.ErrInvalidData
		}
		result := db.Create(&newUserLog)
		return result.Error == nil, result.Error
	}

	// 记录存在：根据存在的字段更新
	var updateData map[string]interface{}

	if login_time > 0 {
		updateData = map[string]interface{}{"login_time": login_time}
	} else if operation_time > 0 {
		updateData = map[string]interface{}{"operation_time": operation_time}
	} else {
		return false, gorm.ErrInvalidData
	}
	result = db.Model(&userLog).Where("acid = ?", acid).Updates(updateData)
	return result.Error == nil, result.Error
}

func UpdateUserLog(userid int, free_creadit int, member_creadit int, added_creadit int) {
	var mindlog UserLog
	var userLog UserLog
	value := db.Where("acid = ?", userid).Order("id desc").Find(&mindlog)
	userLog.FreeCreadit = free_creadit
	userLog.MemberCreadit = member_creadit
	userLog.AddedCreadit = added_creadit
	if value.RowsAffected == 0 {
		userLog.Acid = userid
		db.Model(&UserLog{}).Create(&userLog)
	} else {
		all_creadit := free_creadit + member_creadit + added_creadit
		db.Model(&UserLog{}).Where("acid = ?", userid).Update(map[string]interface{}{
			"FreeCreadit":   free_creadit,
			"MemberCreadit": member_creadit,
			"AddedCreadit":  added_creadit,
			"AllCreadit":    all_creadit,
		})
	}
}
func GetUserLog(userid int) (device UserLog) {
	db.Where("acid = ?", userid).Order("id desc").Find(&device)
	return
}
func DeleteCreadit(userid int, all_creadit int) {
	db.Model(&UserLog{}).Where("acid = ?", userid).Update(map[string]interface{}{
		"AllCreadit": all_creadit,
	})
}
